#include <stdio.h>
#include <stdlib.h>

#define IF_BREAK(cond) if (cond) { break; }

static const char encrpyt_key[] = {'p', 'w', 'd', '1', '2', '3'};

unsigned char *getFileData(const char *filename, int *filelength)
{
	FILE *fp = NULL;
	fp = fopen(filename, "rb");

	fseek(fp, 0, SEEK_END);
	int len = ftell(fp);
	rewind(fp);

	unsigned char *buff = malloc(len);
	fread(buff, 1, len, fp);
	fclose(fp);

	if (buff && len > 0) {
		*filelength = len;
	}

	return buff;
}

void writeFileData(const char *filename, unsigned char *data, int len)
{
	FILE *fp = NULL;
	fp = fopen(filename, "wb");
	fwrite(data, 1, len, fp);
	fclose(fp);
}

void encrypt(unsigned char *input, int inputlen, const char *key, int keylen)
{
	int i;
	int count = 0;
	for (i=0; i<inputlen; ++i) {
		*input ^= key[count];
		++input;
		++count;
		if (count >= keylen) {
			count = 0;
		}
	}
}

void decrypt(unsigned char *input, int inputlen, const char *key, int keylen)
{
	int i;
	int count = 0;
	for (i=0; i<inputlen; ++i) {
		*input ^= key[count];
		++input;
		++count;
		if (count >= keylen) {
			count = 0;
		}
	}
}

int main(int argc, char *argv[])
{
	do {
		IF_BREAK(argc == 1);

		char *filename = argv[1];
		int bEncrypt = atoi(argv[2]) == 1;

		IF_BREAK(filename == NULL);

		int len = 0;
		unsigned char *data = getFileData(filename, &len);

		printf("encrypt file:%s mode=%d len=%d content=%s\n", filename, bEncrypt, len, data);

		IF_BREAK(len==0);

		int keylen = sizeof(encrpyt_key) / sizeof(char);
		if (bEncrypt) {
			encrypt(data, len, encrpyt_key, keylen);
		} else {
			decrypt(data, len, encrpyt_key, keylen);
		}

		writeFileData(filename, data, len);

		free(data);
	} while(0);

	return 0;
}